package com.lsu.app.controller.Teacher;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsu.app.bean.*;
import com.lsu.app.config.target.RequestRoles;
import com.lsu.app.service.*;
import com.lsu.app.tool.AESUtil;
import com.lsu.app.tool.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hjj
 * @date 2023/10/16 19:01
 */
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/infos")
public class InfoController {
    @Autowired
    private HttpServletRequest request;

    private final VocabularyService vocabularyService;
    private final NoticeService noticeService;
    private final ClickDateService clickDateService;
    private final CourseService courseService;
    private final CollectService collectService;
    private final CommentService commentService;
    private final ResourceService resourceService;
    private final UserService userService;
    private final CourseScoreService courseScoreService;
    public InfoController(VocabularyService vocabularyService, NoticeService noticeService, ClickDateService clickDateService, CourseService courseService, CollectService collectService, CommentService commentService, ResourceService resourceService, UserService userService, CourseScoreService courseScoreService) {
        this.vocabularyService = vocabularyService;
        this.noticeService = noticeService;
        this.clickDateService = clickDateService;
        this.courseService = courseService;
        this.collectService = collectService;
        this.commentService = commentService;
        this.resourceService = resourceService;
        this.userService = userService;
        this.courseScoreService = courseScoreService;
    }

    @RequestRoles({"teacher"})
    @GetMapping("/get")
    @ApiOperation("获取可视化界面数据")
    public R<InfoData> get(){
        Integer teacherId = (Integer) request.getSession().getAttribute("id");
        Integer allStudents = collectService.CountByTeacherId(teacherId);//总关注学生数
        Integer allComments = commentService.CountCommentsByTeacherId(teacherId);//总评论数
        Integer allCourses = courseService.CountCourseNumByTeacherId(teacherId);//总课程数
        Integer allClicks = courseService.CountClickByTeacherId(teacherId);//获取总点击量
        List<Integer> courseIds = courseService.getCourseIdsOfTeacherId(teacherId);
        int allStar = (int) courseScoreService.count(new LambdaQueryWrapper<CourseScore>().in(CourseScore::getCourseId,courseIds));//总条数
        int fiveStar= (int) courseScoreService.count(new LambdaQueryWrapper<CourseScore>().eq(CourseScore::getScore,5).in(CourseScore::getCourseId,courseIds));//五星平均数目
        int fourStar=(int) courseScoreService.count(new LambdaQueryWrapper<CourseScore>().eq(CourseScore::getScore,4).in(CourseScore::getCourseId,courseIds));//四星平均数目
        int threeStar=(int) courseScoreService.count(new LambdaQueryWrapper<CourseScore>().eq(CourseScore::getScore,3).in(CourseScore::getCourseId,courseIds));//三星平均数目
        int twoStar=(int) courseScoreService.count(new LambdaQueryWrapper<CourseScore>().eq(CourseScore::getScore,2).in(CourseScore::getCourseId,courseIds));//二星平均数目
        int oneStar=(int) courseScoreService.count(new LambdaQueryWrapper<CourseScore>().eq(CourseScore::getScore,1).in(CourseScore::getCourseId,courseIds));//一星平均数目
        DecimalFormat df = new DecimalFormat("#.#");
        //获取今天开始日期
        String valScore=df.format((5*fiveStar+fourStar*4+threeStar*3+twoStar*2+oneStar)/allStar);//平均评分
        return R.success(new InfoData(allStudents,allComments,allCourses,allClicks,fiveStar,fourStar,threeStar,twoStar,oneStar,valScore,
                clickDateService.getRate(teacherId)));
    }
    @RequestRoles({"teacher"})
    @GetMapping("/getXY")
    @ApiOperation("获取可视化界面数据折线图[点击次数-时间]")
    public R<XYData> getXYDate(){
        Integer teacherId = (Integer) request.getSession().getAttribute("id");
        String[] dates = AESUtil.getPreviousDates(30);
        Integer[] nums = clickDateService.getClicksByDays(30,teacherId);
        return R.success(new XYData(dates,nums));
    }
    @RequestRoles({"teacher"})
    @GetMapping("/getVoc")
    @ApiOperation("获取词云数据")
    public R<List<Vocabulary>> getVoc(){
        Integer teacherId = (Integer) request.getSession().getAttribute("id");
//        List<Integer> courseIds = courseService.getCourseIdsOfTeacherId(teacherId);
//        List<Vocabulary> list = vocabularyService.list(new LambdaQueryWrapper<Vocabulary>().in(Vocabulary::getCourseId,courseIds));
        return R.success(vocabularyService.getVocasByCourseIds(teacherId));
    }
    @RequestRoles({"teacher"})
    @GetMapping("/getVocXY")
    @ApiOperation("获取词云数据折线图")
    public R<VoXYData> getVoXYData(){
        Integer teacherId = (Integer) request.getSession().getAttribute("id");
        List<Course> courses  = courseService.list(new LambdaQueryWrapper<Course>().eq(Course::getTeacherId, teacherId));
        String[] X = new String[courses.size()];
        Integer[] Y1 = new Integer[courses.size()];
        Integer[] Y2 = new Integer[courses.size()];
        Integer[] Y3 = new Integer[courses.size()];
        for(int i =0;i<courses.size();i++){
            Course course = courses.get(i);
            X[i]=course.getCourseName();
            Y1[i]=vocabularyService.getCountByCourseIdAndType(course.getId(),1);
            Y2[i]=vocabularyService.getCountByCourseIdAndType(course.getId(),2);
            Y3[i]=vocabularyService.getCountByCourseIdAndType(course.getId(),3);
        }
        return R.success(new VoXYData(X,Y1,Y2,Y3));
    }

    @RequestRoles({"teacher"})
    @GetMapping("/getCourseData")
    @ApiOperation("获取课程反馈及高频词")
    public R<Page<CourseFeelback>> getFeelBack(
        @ApiParam("当前页")@RequestParam("pageCur") Integer pageCur,
        @ApiParam("页码")@RequestParam("pageSize") Integer pageSize
    ){
        Integer teacherId = (Integer) request.getSession().getAttribute("id");
        Page<Course> coursePage = courseService.page(new Page<>(pageCur,pageSize),
                new LambdaQueryWrapper<Course>().eq(Course::getTeacherId,teacherId));
        Page<CourseFeelback> page = new Page<>(pageCur,pageSize,coursePage.getTotal());
        List<CourseFeelback> list = new ArrayList<>();
        for (Course record : coursePage.getRecords()) {
            String[] str = vocabularyService.getQuWordsByCourseId(record.getId());
            list.add(new CourseFeelback(record.getId(),record.getCourseName(),record.getClickNum(),str));
        }
        page.setRecords(list);
        return R.success(page);
    }

    @RequestRoles({"teacher"})
    @PostMapping("/sends")
    @ApiOperation("邮件回复词云词汇学生")
    public R<String> sends(
        @ApiParam("词云单词")@RequestParam("word") String word,
        @ApiParam("标题")@RequestParam("title") String title,
        @ApiParam("内容")@RequestParam("content") String content
    ){
        if (title.equals("")||content.equals("")){
            return R.err("请勿空回复");
        }
        Integer userId = (Integer) request.getSession().getAttribute("id");
        List<Integer> courseIds = vocabularyService.getCourseIdByWord(word);
        for (Integer courseId : courseIds) {
            List<Integer> stuIds = vocabularyService.getUserIdByWord(word,courseId);
            for (Integer stuId : stuIds) {
                Notice notice = new Notice(3,userId,title,content,courseId,stuId,1, LocalDateTime.now().toString());
                noticeService.save(notice);
            }
        }
        return R.success("发送成功");
    }

    @RequestRoles({"teacher"})
    @GetMapping("/getCourseComs")
    @ApiOperation("获取课程评论[分页]")
    public R<Page<Comment>> getPageComments(
        @ApiParam("当前页")@RequestParam("pageCur") Integer pageCur,
        @ApiParam("页码")@RequestParam("pageSize") Integer pageSize
    ){
        Integer teacherId = (Integer) request.getSession().getAttribute("id");
        List<Integer> ids = courseService.getCourseIdsOfTeacherId(teacherId);
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Comment::getLinkId,ids).eq(Comment::getType,1);
        List<Integer> resIds = new ArrayList<>();
        for (Integer id : ids) {
            resIds.addAll(resourceService.getIdsByCourseId(id));
        }
        wrapper.or().in(Comment::getLinkId,resIds).eq(Comment::getType,2);
        Page<Comment> page = commentService.page(new Page<>(pageCur,pageSize),wrapper);
        for (Comment record : page.getRecords()) {
            if(record.getType()==1){
                record.setLinkCoverImg(resourceService.getCoverImgUrlByCourseId(record.getLinkId()));
                record.setLinkName(courseService.getCourseNameById(record.getLinkId()));
            }else if(record.getType()==2){
                record.setLinkCoverImg(resourceService.getCourseCoverUrlByVideoId(record.getLinkId()));
                record.setLinkName(resourceService.getCourseNameByVideoId(record.getLinkId()));
            }
            record.setNickname(userService.getNameById(record.getUserId()));
        }
        return R.success(page);
    }

}
